package bootstrap

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/viper"
	"log"
	"os"
	"user/dao"
	"user/utils"
)

func Bootstrap() {
	initConfig()
	initDB()
}

func initConfig() {
	path, _ := os.Getwd()
	viper.AddConfigPath(path + "/config/")
	viper.SetConfigName("application")
	viper.SetConfigType("yml")
	if err := viper.ReadInConfig(); err != nil {
		panic(err)
	}
}

func initDB() {
	dbconfig := viper.GetStringMap("database")
	driver := dbconfig["driver"].(string)
	user := dbconfig["username"]
	password := dbconfig["password"]
	host := dbconfig["host"]
	port := dbconfig["port"]
	database := dbconfig["database"]
	charset := dbconfig["charset"]
	dsn := fmt.Sprintf("%s:%d@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local", user, password, host, port, database, charset)

	db, err := sql.Open(driver, dsn)
	utils.CheckError(err)
	log.Println("database连接成功")
	dao.SetDB(db)

}
